﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace CoreHelper.Encrypt
{
    /// <summary>
    /// SHA256加密
    /// </summary>
    public class SHA256
    {
        #region SHA256加密
        /// <summary>
        /// SHA256加密，输出16进制小写
        /// </summary>
        /// <param name="data">要加密的字符串</param>
        /// <param name="enc">编码方式，可选值：Encoding.UTF8（默认,最常用），Encoding.Default，Encoding.ASCII，Encoding.Unicode</param>
        /// <param name="outFormat">输出格式，可先值有：16进制小写Hex_x2（默认），16进制大写Hex_X2，Base64，普通字符串str</param>
        /// <returns>输出16进制小写</returns>
        public static string sha256Encrypt(string data, Encoding enc = null, string outFormat = "Hex_x2")
        {
            if (enc == null)
            {
                enc = Encoding.UTF8;
            }
            byte[] bytes = enc.GetBytes(data);
            byte[] hash = SHA256Managed.Create().ComputeHash(bytes);

            string outstr = "";
            switch (outFormat)
            {
                case "Hex_x2":
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < hash.Length; i++)
                    {
                        builder.Append(hash[i].ToString("x2"));
                    }

                    outstr = builder.ToString();
                    break;
                case "Hex_X2":
                    StringBuilder builder1 = new StringBuilder();
                    for (int i = 0; i < hash.Length; i++)
                    {
                        builder1.Append(hash[i].ToString("X2"));
                    }

                    outstr = builder1.ToString();
                    break;
                case "Base64":
                    outstr = Convert.ToBase64String(bytes);
                    break;
                case "str":
                    outstr = enc.GetString(bytes);
                    break;
            }
            return outstr;
        }
        #endregion
    }
}
